package cn.yx.common.i18n.service;

import cn.yx.common.i18n.constant.I18nConstant;
import cn.yx.common.redis.service.RedisService;
import cn.yx.sys.remote.cond.SysI18nMessageRemoteCond;
import cn.yx.sys.remote.dto.SysI18nMessageRemoteDto;
import cn.yx.sys.remote.service.SysI18nMessageRemoteService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * <p>i18n消息服务类</p>
 *
 * @author Wgssmart
 */
@Component
@Slf4j
public class I18nMessageCacheService {

    private static final String MESSAGE_KEY_PREFIX = "cn.yx.";

    @DubboReference(check = false)
    private SysI18nMessageRemoteService sysI18nMessageRemoteService;

    private final RedisService redisService;

    public I18nMessageCacheService(RedisService redisService) {
        this.redisService = redisService;
    }

    /**
     * 调用远程接口查询国际化信息，如果是指定了messageKey的消息，则缓存到Redis，直接指定返回消息的不缓存到Redis
     *
     * @param messageKey 消息Key
     * @return
     */
    @Cacheable(key = "#messageKey", cacheNames = I18nConstant.REDIS_CACHE_NAMES, condition = "#messageKey.startsWith('cn.yx.')")
    public SysI18nMessageRemoteDto getSysI18nMessage(String messageKey) {
        String lang = redisService.get(I18nConstant.I18N_LANG_KEY).toString();
        if (!messageKey.startsWith(MESSAGE_KEY_PREFIX)) {
            // 不是cn.yx.开头的messageKey，不需要调用远程服务去查询消息，直接返回消息，且不需要缓存到Redis
            log.info("directly return message, message key: {}", messageKey);
            return createSysI18nMessageDto(messageKey, lang);
        }
        SysI18nMessageRemoteCond sysI18nMessageRemoteCond = new SysI18nMessageRemoteCond();
        sysI18nMessageRemoteCond.setLang(lang);
        sysI18nMessageRemoteCond.setMessageKey(messageKey);
        SysI18nMessageRemoteDto sysI18nMessageRemoteDto = sysI18nMessageRemoteService.getOne(sysI18nMessageRemoteCond);
        if (Objects.nonNull(sysI18nMessageRemoteDto)) {
            log.info("get i18n message from remote service, message key: {}", messageKey);
            return sysI18nMessageRemoteDto;
        }
        // 通过messageKey查询不到消息，则直接返回消息
        log.warn("can not get i18n message from remote service, message key: {}", messageKey);
        return createSysI18nMessageDto(messageKey, lang);
    }

    private SysI18nMessageRemoteDto createSysI18nMessageDto(String messageKey, String lang) {
        SysI18nMessageRemoteDto sysI18nMessageRemoteDto = new SysI18nMessageRemoteDto();
        sysI18nMessageRemoteDto.setMessageKey(messageKey);
        sysI18nMessageRemoteDto.setLang(lang);
        sysI18nMessageRemoteDto.setMessage(messageKey);
        return sysI18nMessageRemoteDto;
    }

}
